package com.huike.pmps.quartz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huike.pmps.dao.PODao;
import com.huike.pmps.model.constants.GlobalConstants;
import com.huike.pmps.model.entity.Dictionary;
import com.huike.pmps.model.entity.PO;
import com.huike.pmps.service.DictionaryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 作者：谌贵斌(黑桃K)
 * 日期: 2888-08-08
 * 老师QQ: 272488352
 * 官方QQ交流群: 377748272
 * 刀客程序员官网：http://www.daoke360.com
 * 刀客程序员淘宝旗舰店：https://daoke360.taobao.com/
 */
@Component
@Slf4j
public class CrontabTask {
    @Autowired
    private PODao poDao;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    DictionaryService dictionaryService;
    /**
     * 定时检测po合同是否过期
     */
    @Scheduled(
            initialDelay = 3000, //当任务启动后，等待多久执行
            fixedDelay = 30 * 60 * 1000//每隔多久执行方法
    )
    public void updatePOState() {
        QueryWrapper<PO> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id");
        //合同交付日期小于当前时间
        queryWrapper.lt("contract_delivery_date", new Date());
        //PO状态状态是进行中（ PO状态(1进行中、2已完成、3已过期) ）
        queryWrapper.eq("po_state", GlobalConstants.PO_STATE_START);
        List<PO> poList = poDao.selectList(queryWrapper);
        if (poList.size() > 0) {
            for (PO po : poList) {
                po.setPoState(GlobalConstants.PO_STATE_EXPIRED);
            }
            int count = poDao.updatePOState(poList);
            System.out.println(count + "条PO合同已过期");
        }
        System.out.println("执行了定时任务:检测po合同是否过期");
    }

    /**
     * 定时更新redis缓存
     */
    @Scheduled(
            initialDelay = 1000, //当任务启动后，等待多久执行
            fixedDelay = 5 * 60 * 1000//每隔多久执行方法
            //cron = "0 30 7,9,12,15,18 * * ?"
    )
    public void updateDictionary(){
        //将字典数据存入redis
        List<Dictionary> dictionaries = dictionaryService.selectList();
        for (Dictionary dictionary : dictionaries) {
            redisTemplate.opsForHash().put(GlobalConstants.REDIS_HASH_DICTIONARY_DATA, dictionary.getId(), dictionary.getName());
        }
        log.info("执行了定时任务:加载数据字典到redis中");
    }

}
